package com.bruce.nettyDemo.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * Created by bruce on 19/3/30 -- 9:52
 * 自定义的助手类
 */
public class WSHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static volatile int clientCount = 0;
    //用户记录和管理所有的客户端的channel
    private static ChannelGroup clientList = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx,
                                TextWebSocketFrame msg) throws Exception {
        //获取客户端发送来的消息
        String content = msg.text();
        System.out.println("接收到的消息是:" + content);
        System.out.println("在线人数是:" + clientCount);
//        群发
        clientList.writeAndFlush(new TextWebSocketFrame("发送的消息是" + content + ">>>在线人数是: " + clientCount + "\n"));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clientList.add(ctx.channel());
        clientCount++;
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        clientList.remove(ctx.channel());
        clientCount--;
    }
}
